package com.jic.market.impl.skill;

import com.beust.jcommander.internal.Lists;
import com.jic.common.base.vo.AdminOperate;
import com.jic.common.base.vo.Page;
import com.jic.common.base.vo.PageResult;
import com.jic.common.base.vo.RestResult;
import com.jic.common.utils.IDUtils;
import com.jic.manager.api.rest.ManagerMerchantApi;
import com.jic.manager.api.rest.ManagerStoreApi;
import com.jic.manager.request.MerchantRequest;
import com.jic.manager.response.Mestore;
import com.jic.market.common.enums.DeleteFlagEnum;
import com.jic.market.common.enums.MerchantTypeEnum;
import com.jic.market.common.enums.MutexFlagEnum;
import com.jic.market.common.enums.ProductScopeTypeEnum;
import com.jic.market.common.enums.TypeOfProductEnum;
import com.jic.market.entity.GoodsSku;
import com.jic.market.entity.GoodsSpu;
import com.jic.market.entity.PromotionEntity;
import com.jic.market.entity.PromotionMerchantEntity;
import com.jic.market.entity.PromotionMerchantProductEntity;
import com.jic.market.entity.PromotionMutex;
import com.jic.market.entity.Tag;
import com.jic.market.entity.base.BaseActivity;
import com.jic.market.entity.mutex.MutexModel;
import com.jic.market.entity.mutex.MutexProductEntity;
import com.jic.market.entity.mutex.MutexResultContext;
import com.jic.market.entity.skill.ActivityMerchantConfig;
import com.jic.market.entity.skill.ActivitySkillGoodsConfig;
import com.jic.market.entity.skill.ActivityStoreConfig;
import com.jic.market.entity.skill.SkillActivityConfig;
import com.jic.market.entity.skill.SkillActivityTimeConfig;
import com.jic.market.enums.FrontPromotionTypeEnum;
import com.jic.market.enums.PromotionTypeEnum;
import com.jic.market.mapper.PromotionEntityMapper;
import com.jic.market.mapper.PromotionMerchantEntityMapper;
import com.jic.market.mapper.PromotionMerchantProductEntityMapper;
import com.jic.market.mapper.TagMapper;
import com.jic.market.mapper.base.BaseActivityMapper;
import com.jic.market.mapper.skill.ActivitySkillGoodsConfigMapper;
import com.jic.market.mapper.skill.SkillActivityConfigMapper;
import com.jic.market.orm.Pagination;
import com.jic.market.request.BaseRequest;
import com.jic.market.request.CouponDetailRequest;
import com.jic.market.request.MemberGradeInfoRequest;
import com.jic.market.request.PromotionMemberGradeRequest;
import com.jic.market.request.after.TellAddAllocationRequest;
import com.jic.market.request.manager.base.MerchantDeleteRequest;
import com.jic.market.request.manager.base.MerchantInfo;
import com.jic.market.request.manager.base.PromotionIdRequest;
import com.jic.market.request.manager.base.StoreDeleteRequest;
import com.jic.market.request.manager.base.StoreInfo;
import com.jic.market.request.manager.coupon.CouponTemplatRequest;
import com.jic.market.request.manager.skill.SkillBatchDeleteRequest;
import com.jic.market.request.manager.skill.SkillBatchQueryRequest;
import com.jic.market.request.manager.skill.SkillCheckRequest;
import com.jic.market.request.manager.skill.SkillConfigAddRequest;
import com.jic.market.request.manager.skill.SkillConfigQueryPageRequest;
import com.jic.market.request.manager.skill.SkillConfigUpdateaRequest;
import com.jic.market.request.manager.skill.SkillDeleteTimeOfDateRequest;
import com.jic.market.request.manager.skill.SkillGoodsDeleteRequest;
import com.jic.market.request.manager.skill.SkillGoodsIdsRequest;
import com.jic.market.request.manager.skill.SkillGoodsInfo;
import com.jic.market.request.manager.skill.SkillGoodsRequest;
import com.jic.market.request.manager.skill.SkillImagesUrlUpdateRequest;
import com.jic.market.request.manager.skill.SkillMerchantAddRequest;
import com.jic.market.request.manager.skill.SkillStoreAddRequest;
import com.jic.market.request.manager.skill.SkillTimeInfo;
import com.jic.market.response.manager.goods.GoodsQueryInfo;
import com.jic.market.response.manager.skill.SkillConfigQueryResponse;
import com.jic.market.response.manager.skill.SkillGoodsQueryResponse;
import com.jic.market.response.manager.skill.SkillGoodsTimeResponse;
import com.jic.market.response.manager.skill.SkillMerchantResponse;
import com.jic.market.response.manager.skill.SkillStoreQueryResponse;
import com.jic.market.response.manager.skill.SkillStoreResponse;
import com.jic.market.response.manager.skill.SkillTimeQueryResponse;
import com.jic.market.response.manager.skill.SkillTimeResponseInfo;
import com.jic.market.service.PromotionMemberGradeService;
import com.jic.market.service.PromotionMutexService;
import com.jic.market.service.PromotionTemplateService;
import com.jic.market.service.allocation.AllocationLogicService;
import com.jic.market.service.base.BaseActivityService;
import com.jic.market.service.mutex.MutexService;
import com.jic.market.service.skill.ActivityMerchantConfigService;
import com.jic.market.service.skill.ActivitySkillGoodsConfigService;
import com.jic.market.service.skill.ActivityStoreConfigService;
import com.jic.market.service.skill.SkillActivityConfigService;
import com.jic.market.service.skill.SkillActivityTimeConfigService;
import com.jic.product.after.api.ProductListApi;
import com.jic.product.after.request.GoodsPageQueryRequest;
import com.jic.product.after.response.ProductStoreInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.Collectors;

/**
 * 秒杀基础信息配置表
 *
 * @author : seven
 * @version : v1.0.0
 * @email : 774329481@qq.com
 * @since : 2020-03-12 04:31:17
 */
@Slf4j
@Service
public class SkillActivityConfigServiceImpl implements SkillActivityConfigService {

    private static ExecutorService executorServiceR = Executors.newFixedThreadPool(20);

    @Autowired
    private SkillActivityConfigMapper skillActivityConfigMapper;
    @Autowired
    BaseActivityService baseActivityService;

    @Autowired
    ActivitySkillGoodsConfigMapper activitySkillGoodsConfigMapper;

    @Autowired
    SkillActivityTimeConfigService skillActivityTimeConfigService;

    @Autowired
    ActivityMerchantConfigService activityMerchantConfigService;
    @Autowired
    ActivityStoreConfigService activityStoreConfigService;
    @Autowired
    ActivitySkillGoodsConfigService activitySkillGoodsConfigService;
    @Autowired
    PromotionTemplateService promotionTemplateService;

    @Resource
    private PromotionEntityMapper promotionEntityMapper;

    @Resource
    private PromotionMerchantProductEntityMapper promotionMerchantProductEntityMapper;

    @Autowired
    AllocationLogicService allocationLogicService;

    @Autowired
    private TagMapper tagMapper;
    @Resource
    private ManagerMerchantApi managerMerchantApi;
    @Resource
    private ManagerStoreApi mestoreService;

    @Resource
    private MutexService mutexService;

    @Resource
    private PromotionMutexService promotionMutexService;

    @Autowired
    private PromotionMemberGradeService promotionMemberGradeService;

    @Resource
    private ProductListApi productListApi;

    @Autowired
    private BaseActivityMapper baseActivityMapper;

    @Override
    public long insert(SkillActivityConfig skillActivityConfig) {
        // TODO 权限相关
        skillActivityConfig.setDeleteFlag(false);
        long flag = skillActivityConfigMapper.insert(skillActivityConfig);
        return flag;
    }

    @Override
    public long delete(String promotionId) {
        return skillActivityConfigMapper.delete(promotionId);
    }

    @Override
    public long update(SkillActivityConfig skillActivityConfig) {
        return skillActivityConfigMapper.update(skillActivityConfig);
    }

    @Override
    public SkillActivityConfig queryByPrimaryKey(Long id) {
        return skillActivityConfigMapper.queryByPrimaryKey(id);
    }

    @Override
    public List<SkillActivityConfig> query(SkillActivityConfig skillActivityConfig) {
        return skillActivityConfigMapper.query(skillActivityConfig);
    }

    @Override
    public PageResult<SkillActivityConfig> queryPage(SkillActivityConfig skillActivityConfig, Page pageQuery) {
        //计算下标
        int startIndex = (pageQuery.getStart() - 1) * pageQuery.getLimit();
        List<SkillActivityConfig> list = skillActivityConfigMapper.queryPage(startIndex, pageQuery.getLimit(), skillActivityConfig);
        long count = skillActivityConfigMapper.queryPageCount(skillActivityConfig);
        PageResult pageResult = new PageResult();
        pageResult.setRows(list);
        pageResult.setTotal(count);
        return pageResult;
    }

    @Override
    public RestResult<String> addSkillConfig(SkillConfigAddRequest skillConfigAddRequest) {
        RestResult<String> result = new RestResult<>();
        if (skillConfigAddRequest.getStartTime() != null && skillConfigAddRequest.getStartTime().getTime() < System.currentTimeMillis()) {
            result.setCode("5000");
            result.setMsg("活动开始时间不能小于当前时间!");
            return result;
        }

        String code = IDUtils.GenerateBillNo(skillConfigAddRequest.getFrontPromType());

        PromotionEntity promotionEntity = new PromotionEntity();

        BeanUtils.copyProperties(skillConfigAddRequest, promotionEntity);
        promotionEntity.setPromType(PromotionTypeEnum.SECKILL.getCode());
        promotionEntity.setFrontPromType(FrontPromotionTypeEnum.SECKILL_SECKILL.getCode());
        promotionEntity.setPromotionCode(code);
        promotionEntity.setCreatorName(skillConfigAddRequest.getAdminOperate().getOperateName());
        promotionEntity.setCreator(skillConfigAddRequest.getAdminOperate().getOperator());
        promotionEntity.setUpdator(skillConfigAddRequest.getAdminOperate().getOperator());
        promotionEntity.setUpdatorName(skillConfigAddRequest.getAdminOperate().getOperateName());
        promotionEntity.setDeptId(skillConfigAddRequest.getAdminOperate().getDeptId());
        promotionEntity.setDeptType(skillConfigAddRequest.getAdminOperate().getDeptType().getCode());
        promotionEntity.setDeleteFlag(DeleteFlagEnum.UN_DELETE.getCode());
        promotionEntity.setStatus(9);
//        promotionEntity.setLabel(StringUtils.isEmpty(skillConfigAddRequest.getLabel()) ? null : skillConfigAddRequest.getLabel());
        promotionEntity.setParcelsFlag(Integer.parseInt(skillConfigAddRequest.getParcelsFlag()));
        promotionEntity.setChannelId(skillConfigAddRequest.getChannelId());
        //保存到统一promotion表中
//        long insert = baseActivityMapper.insert(baseActivity);
        int insert = promotionEntityMapper.insert(promotionEntity);

        log.info("添加秒杀基础配置======>>>>>>>>活动code为:{}==========>?>>>>>>返回:{}", code, insert);

        SkillActivityConfig skillActivityConfig = setSkillActivityConfig(skillConfigAddRequest, promotionEntity.getId().toString());
        insert(skillActivityConfig);

        insertBatchTime(skillConfigAddRequest.getTimeInfoList(), promotionEntity.getId().toString());

        MemberGradeInfoRequest memberGradeInfoRequest = new MemberGradeInfoRequest();
        memberGradeInfoRequest.setPromotionId(promotionEntity.getId().toString());
        memberGradeInfoRequest.setPromotionCode(promotionEntity.getPromotionId());
        memberGradeInfoRequest.setPromType(PromotionTypeEnum.SECKILL.getCode());
        memberGradeInfoRequest.setFrontPromType(30);
        memberGradeInfoRequest.setPromotionMemberGradeList(skillConfigAddRequest.getPromotionMemberGradeList());
        promotionMemberGradeService.addMemberGrade(memberGradeInfoRequest);

        return RestResult.success(promotionEntity.getId().toString());
    }

    @Override
    public RestResult<SkillConfigQueryResponse> querySkillConfig(PromotionIdRequest promotionIdRequest) {
        SkillConfigQueryResponse response = new SkillConfigQueryResponse();
        PromotionEntity promotionEntity = promotionEntityMapper.queryById(Long.valueOf(promotionIdRequest.getPromotionId()));

        if (promotionEntity == null) {
            return RestResult.success(null);
        }

//        PromotionEntity promotionEntity = baseActivityMapper.queryByPromotionId(Long.valueOf(promotionIdRequest.getPromotionId()));

        BeanUtils.copyProperties(promotionEntity, response);
        response.setChannelCodes(getArrayList(promotionEntity.getChannelCodes()));
        response.setParcelsFlag(promotionEntity.getParcelsFlag().toString());
        response.setPromotionCode(promotionEntity.getPromotionId());
        response.setStatus(promotionEntity.getStatus().toString());
        response.setParentAllocationScale(promotionEntity.getParentAllocationScale() == null ? "" : promotionEntity.getParentAllocationScale().toString());
        response.setChildAllocationScale(promotionEntity.getChildAllocationScale() == null ? "" : promotionEntity.getChildAllocationScale().toString());
        response.setMerchantAllocationScale(promotionEntity.getMerchantAllocationScale() == null ? "" : promotionEntity.getMerchantAllocationScale().toString());
        response.setStoreAllocationScale(promotionEntity.getStoreAllocationScale() == null ? "" : promotionEntity.getStoreAllocationScale().toString());
        SkillActivityConfig skillActivityConfig = skillActivityConfigMapper.queryByPromotionId(promotionIdRequest.getPromotionId());
        if (skillActivityConfig != null) {
            response.setOverLimitRule(skillActivityConfig.getOverLimitRule());
            response.setWarmUpTime(skillActivityConfig.getWarmUpTime());

            List<String> imagesList = getImagesUrlList(skillActivityConfig.getImagesUrls());
            response.setImagesUrls(imagesList);
        }

        List<PromotionMemberGradeRequest> promotionMemberGradeRequestList = promotionMemberGradeService.queryMemberGrade(String.valueOf(promotionEntity.getId()));
        response.setPromotionMemberGradeList(promotionMemberGradeRequestList);

        List<SkillTimeResponseInfo> responseInfoList = getSkillTimeResponseInfoList(promotionIdRequest.getPromotionId());
        response.setResponseInfoList(responseInfoList);
        response.setEditFlag(Long.valueOf(promotionEntity.getDeptId()).equals(promotionIdRequest.getAdminOperate().getDeptId()) ? true : false);
        return RestResult.success(response);
    }

    @Resource
    private PromotionMerchantEntityMapper promotionMerchantEntityMapper;

    @Override
    public RestResult<Boolean> addSkillMerchantConfig(SkillMerchantAddRequest skillMerchantAddRequest) {
        if (CollectionUtils.isEmpty(skillMerchantAddRequest.getMerchantInfoList())) {
            return RestResult.success(true);
        }
        skillMerchantAddRequest.getMerchantInfoList().stream().forEach(temp -> {
//            ActivityMerchantConfig config = new ActivityMerchantConfig();
//            BeanUtils.copyProperties(temp, config);
//            config.setPromotionId(skillMerchantAddRequest.getPromotionId());
//            activityMerchantConfigService.insert(config);
            PromotionMerchantEntity promotionMerchantEntity = new PromotionMerchantEntity();
            promotionMerchantEntity.setMerchantId(Long.valueOf(temp.getMerchantId()));
            promotionMerchantEntity.setMerchantType(MerchantTypeEnum.MERCHANT.getCode());
            promotionMerchantEntity.setMerchantName(temp.getMerchantName());
            promotionMerchantEntity.setDeleteFlag(DeleteFlagEnum.UN_DELETE.getCode());
            promotionMerchantEntity.setOrgNumber(temp.getOrgNumber());
            promotionMerchantEntity.setMerchantTypeManager(temp.getMerchantTypeId());
            promotionMerchantEntity.setPromotionId(Long.valueOf(skillMerchantAddRequest.getPromotionId()));
            promotionMerchantEntityMapper.insert(promotionMerchantEntity);
        });
        return RestResult.success(true);
    }

    @Override
    public RestResult<SkillMerchantResponse> querySkillMerchant(CouponDetailRequest request) {
        SkillMerchantResponse response = new SkillMerchantResponse();
        response.setPromotionId(request.getPromotionId());
        //获取当前登录用户有权限的商家列表
        Pagination pagination = Pagination.build(new BaseRequest() {{
            setStart(request.getStart());
            setLimit(request.getLimit());
        }});

        PromotionMerchantEntity promotionEntity = new PromotionMerchantEntity();
        AdminOperate adminOperate = request.getAdminOperate();
        promotionEntity.setPromotionId(Long.valueOf(request.getPromotionId()));
        promotionEntity.setMerchantType(MerchantTypeEnum.MERCHANT.getCode());
        promotionEntity.setMerchantName(request.getMerchantName());
        promotionEntity.setStorecode(request.getStorecode());
        promotionEntity.setStorename(request.getStorename());
        promotionEntity.setOrgNumber(request.getOrgNumber());
        promotionEntity.setDeleteFlag(DeleteFlagEnum.UN_DELETE.getCode());
        //商家
//        List<Long> merchantIds = adminOperate.getMerchantIds();
//        if(CollectionUtils.isEmpty(merchantIds)){
//            response.setMerchantInfoList(new ArrayList<>());
//            response.setTotal(0L);
//            return RestResult.success(response);
//        }
//        promotionEntity.setMerchantIds(merchantIds);
        List<PromotionMerchantEntity> entityList = promotionMerchantEntityMapper.findOfPage(promotionEntity, pagination);
        int count = promotionMerchantEntityMapper.countOfPage(promotionEntity);
        List<MerchantInfo> merchantInfoList = new ArrayList<>();
        entityList.stream().forEach(temp -> {
            MerchantInfo merchantInfo = new MerchantInfo();
            merchantInfo.setMerchantId(temp.getMerchantId().toString());
            merchantInfo.setMerchantName(temp.getMerchantName());
            merchantInfo.setOrgNumber(temp.getOrgNumber());
            merchantInfo.setMerchantTypeId(temp.getMerchantTypeManager());
            merchantInfo.setMerchantTypeName(temp.getMerchantTypeManager().equals("1") ? "自营商家" : "第三方商家");
            merchantInfoList.add(merchantInfo);
        });
        response.setTotal(Long.valueOf(count));
        response.setMerchantInfoList(merchantInfoList);
        return RestResult.success(response);
    }

    @Override
    public RestResult<Boolean> addSkillStoreConfig(SkillStoreAddRequest skillStoreAddRequest) {
        List<StoreInfo> storeInfoList = skillStoreAddRequest.getStoreInfoList();
        if (CollectionUtils.isEmpty(storeInfoList)) {
            return RestResult.success(true);
        }
        storeInfoList.stream().forEach(temp -> {
            PromotionMerchantEntity promotionMerchantEntity = new PromotionMerchantEntity();
            promotionMerchantEntity.setMerchantId(Long.valueOf(temp.getMerchantId()));
            promotionMerchantEntity.setMerchantType(MerchantTypeEnum.STORE.getCode());
            promotionMerchantEntity.setMerchantName(temp.getMerchantName());
            promotionMerchantEntity.setDeleteFlag(DeleteFlagEnum.UN_DELETE.getCode());
            promotionMerchantEntity.setStoreId(Long.valueOf(temp.getStoreId()));
            promotionMerchantEntity.setStorecode(temp.getStoreCode());
            promotionMerchantEntity.setStorename(temp.getStoreName());
            promotionMerchantEntity.setStoreType(temp.getStoreType());
            promotionMerchantEntity.setPromotionId(Long.valueOf(skillStoreAddRequest.getPromotionId()));
            promotionMerchantEntityMapper.insert(promotionMerchantEntity);
        });
        return RestResult.success(true);
    }

    @Override
    public RestResult<SkillStoreResponse> querySkillStore(CouponDetailRequest request) {
        SkillStoreResponse response = new SkillStoreResponse();
        response.setPromotionId(request.getPromotionId());
        //获取当前登录用户有权限的店铺列表
        Pagination pagination = Pagination.build(new BaseRequest() {{
            setStart(request.getStart());
            setLimit(request.getLimit());
        }});

        PromotionMerchantEntity promotionEntity = new PromotionMerchantEntity();
        AdminOperate adminOperate = request.getAdminOperate();
        promotionEntity.setPromotionId(Long.valueOf(request.getPromotionId()));
        promotionEntity.setMerchantType(MerchantTypeEnum.STORE.getCode());
        promotionEntity.setMerchantName(request.getMerchantName());
        promotionEntity.setStorecode(request.getStorecode());
        promotionEntity.setStorename(request.getStorename());
        promotionEntity.setOrgNumber(request.getOrgNumber());
        promotionEntity.setDeleteFlag(DeleteFlagEnum.UN_DELETE.getCode());
        //商家
//        List<Long> merchantIds = adminOperate.getMerchantIds();
//        if(CollectionUtils.isEmpty(merchantIds)){
//            response.setStoreInfoList(new ArrayList<>());
//            response.setTotal(0L);
//            return RestResult.success(response);
//        }
//        promotionEntity.setMerchantIds(merchantIds);
        List<PromotionMerchantEntity> entityList = promotionMerchantEntityMapper.findOfPage(promotionEntity, pagination);
        int count = promotionMerchantEntityMapper.countOfPage(promotionEntity);
        List<StoreInfo> storeInfoList = new ArrayList<>();
        entityList.stream().forEach(temp -> {
            StoreInfo storeInfo = new StoreInfo();
            storeInfo.setMerchantName(temp.getMerchantName());
            storeInfo.setStoreName(temp.getStorename());
            storeInfo.setStoreId(temp.getStoreId().toString());
            storeInfo.setStoreCode(temp.getStorecode());
            storeInfo.setStoreType(temp.getStoreType());
            storeInfoList.add(storeInfo);
        });
        response.setTotal(Long.valueOf(count));
        response.setStoreInfoList(storeInfoList);
        return RestResult.success(response);
    }

    @Override
    public RestResult<SkillTimeQueryResponse> queryTimeOfDate(PromotionIdRequest promotionIdRequest) {
        List<SkillActivityTimeConfig> configList = skillActivityTimeConfigService.queryByPromotionId(promotionIdRequest.getPromotionId());

        SkillTimeQueryResponse response = new SkillTimeQueryResponse();
        response.setPromotionId(promotionIdRequest.getPromotionId());

        if (CollectionUtils.isEmpty(configList)) {
            return RestResult.success(response);
        }

        List<SkillTimeResponseInfo> responseInfoList = new ArrayList<>();

        configList.stream().forEach(temp -> {
            SkillTimeResponseInfo responseInfo = new SkillTimeResponseInfo();
            BeanUtils.copyProperties(temp, responseInfo);
            responseInfo.setSkillTimeId(temp.getTimeId());
            responseInfo.setShowTimeOfDate(temp.getStartTimeOfDate() + "-" + temp.getEndTimeOfDate());
            responseInfoList.add(responseInfo);
        });

        response.setResponseInfoList(responseInfoList);
        return RestResult.success(response);
    }

    @Override
    public RestResult<SkillStoreQueryResponse> queryStoreInfo(PromotionIdRequest promotionIdRequest) {
        List<String> promotionIdList = activityStoreConfigService.queryStoreIdByPromotionId(promotionIdRequest.getPromotionId());

        SkillStoreQueryResponse response = new SkillStoreQueryResponse();
        response.setPromotionId(promotionIdRequest.getPromotionId());

        if (CollectionUtils.isEmpty(promotionIdList)) {
            return RestResult.success(response);
        }

        response.setStoreIdList(promotionIdList);
        return RestResult.success(response);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public RestResult<Boolean> addGoodsConfig(SkillGoodsIdsRequest skillGoodsRequest) {
        //根据SPUid 查询spu和Sku
        List<String> goodsname = new ArrayList<>();
        skillGoodsRequest.getGoodsInfoList().forEach(item -> {
//            GoodsSpu goodsSpu = goodsSpuMapper.queryByPrimaryKey(item);
            List<ProductStoreInfo> productStoreInfos = productListApi.queryProductBySpuList(new GoodsPageQueryRequest() {{
                setId(item);
            }});
            ProductStoreInfo goodsSpu = productStoreInfos.get(0);
            List<ProductStoreInfo> goodsSkuList = productListApi.queryProductBySpuId(new GoodsPageQueryRequest() {{
                setSpuIds(new ArrayList<Long>() {{
                    add(goodsSpu.getId());
                }});
            }});
            //根据spuid查询Sku
//            List<GoodsSku> goodsSkuList = goodsSkuMapper.query(new GoodsSku() {{
//                setGoodsSpuId(goodsSpu.getId().toString());
//            }});

//            GoodsSkuQueryRequest goodsSkuQueryRequest = new GoodsSkuQueryRequest();
//            goodsSkuQueryRequest.setGoodsSpuIds(new ArrayList<Long>(){{
//                add(item);
//            }});
//            RestResult<List<QueryGoodsInfoResponse>> listRestResult = goodsQueryService.queryByGoodsSpuIds(goodsSkuQueryRequest);
//            List<QueryGoodsInfoResponse> goodsInfoResponseList = listRestResult.getData();
            if (CollectionUtils.isEmpty(goodsSkuList)) {
                return;
            }

            final MutexResultContext mutexResultContext = getMutexResultContext(Long.valueOf(skillGoodsRequest.getPromotionId()), goodsSkuList);

            final Set<Long> mutexList = mutexResultContext.getMutexList();
            //final Set<Long> noMutexList = mutexResultContext.getNoMutexList();
            final Map<Long, Set<MutexProductEntity>> mutexPromotionProducts = mutexResultContext.getMutexPromotionProducts();
            //新增spu
            PromotionMerchantProductEntity promotionMerchantProductEntity = spuValueNew(skillGoodsRequest, goodsSpu, mutexList);
            promotionMerchantProductEntityMapper.insert(promotionMerchantProductEntity);
            List<PromotionMerchantProductEntity> promotionMerchantProductEntities = skuValueNew(skillGoodsRequest, goodsSkuList.get(0).getChildren(), mutexList);
            log.info("批量添加Sku===><>>", promotionMerchantProductEntities);
            if(CollectionUtils.isEmpty(promotionMerchantProductEntities)){
//                errorMsg = "商品【"+goodsSpu.getGoodsName()+"】下级不存在SKU";
                goodsname.add(goodsSpu.getChineseName());
                return;
            }
            promotionMerchantProductEntityMapper.insertBatch(promotionMerchantProductEntities);

            promotionMerchantProductEntities.add(promotionMerchantProductEntity);

            //插入互斥表
            mutexPromotionProducts.entrySet().forEach(e -> {
                Set<MutexProductEntity> mutexProductEntitySet = e.getValue();
                List<PromotionMerchantProductEntity> collect = promotionMerchantProductEntities.stream().filter(a -> a.getMpId().equals(e.getKey())).collect(Collectors.toList());
                if (CollectionUtils.isEmpty(collect)) {
                    return;
                }
                promotionMutexService.deleteByPromotionProductId(collect.get(0).getId());
                mutexProductEntitySet.forEach(m -> {
                    promotionMutexService.insert(
                            new PromotionMutex()
                                    .setPromotionId(m.getPromotionId())
                                    .setPromType(m.getPromType())
                                    .setDeleteFlag(DeleteFlagEnum.UN_DELETE.getCode())
                                    .setPromotionMerchantProductId(collect.get(0).getId())
                                    .setCreator(skillGoodsRequest.getAdminOperate().getOperator())
                                    .setCreatorName(skillGoodsRequest.getAdminOperate().getOperateName())
                                    .setUpdator(skillGoodsRequest.getAdminOperate().getOperator())
                                    .setUpdatorName(skillGoodsRequest.getAdminOperate().getOperateName())
                    );
                });
            });
        });
        if(CollectionUtils.isNotEmpty(goodsname)){
            return RestResult.error("5000","操作成功，其中商品【"+String.join(",",goodsname)+"】下级不存在SKU");
        }
        return RestResult.success(true);
    }

    private List<PromotionMerchantProductEntity> skuValueNew(SkillGoodsIdsRequest skillGoodsRequest, List<ProductStoreInfo> goodsSkuList, Set<Long> mutexList) {
        List<PromotionMerchantProductEntity> result = new ArrayList<>();
        goodsSkuList.forEach(sku -> {
            result.add(new PromotionMerchantProductEntity() {{
                setDeptShare(0);
                setMerchantShare(100);
                setPromotionId(Long.valueOf(skillGoodsRequest.getPromotionId()));
                setSkillTimeId(skillGoodsRequest.getSkillTimeId());
                setScopeType(ProductScopeTypeEnum.PRODUCT.getCode());
                setMpId(sku.getId());
                setMpParentId(Long.valueOf(sku.getParentId()));
                setTypeOfProduct(TypeOfProductEnum.GOODS_SKU.getCode());
                setMpCode(sku.getCode());
                setMpName(sku.getChineseName());
                setMerchantId(sku.getMerchantId());
                RestResult<List<MerchantRequest>> merchantResult = managerMerchantApi.queryMerchantListByid(new ArrayList<Long>() {{
                    add(sku.getMerchantId());
                }});
                setMerchantName(merchantResult.getData() == null || CollectionUtils.isEmpty(merchantResult.getData()) ? null : merchantResult.getData().get(0).getName());
                setCategoryName(sku.getCategoryName());
                setMutexFlag(mutexList.contains(sku.getId()) ? MutexFlagEnum.MUTEX.getCode() : MutexFlagEnum.UN_MUTEX.getCode());
                setDeleteFlag(DeleteFlagEnum.UN_DELETE.getCode());
                setStoreId(sku.getStoreId());
                Mestore mestore = mestoreService.queryByPrimaryKey(sku.getStoreId());
                setStoreName(mestore.getStoreName());
            }});
        });
        return result;
    }


    private PromotionMerchantProductEntity spuValueNew(SkillGoodsIdsRequest skillGoodsRequest, ProductStoreInfo goodsSpu, Set<Long> mutexList) {
        return new PromotionMerchantProductEntity() {{
            setDeptShare(0);
            setMerchantShare(100);
            setPromotionId(Long.valueOf(skillGoodsRequest.getPromotionId()));
            setSkillTimeId(skillGoodsRequest.getSkillTimeId());
            setScopeType(ProductScopeTypeEnum.PRODUCT.getCode());
            setMpId(goodsSpu.getId());
            setMpParentId(0L);
            setTypeOfProduct(TypeOfProductEnum.GOODS_SPU.getCode());
            setMpCode(goodsSpu.getCode());
            setMpName(goodsSpu.getChineseName());
            setMerchantId(goodsSpu.getMerchantId());
            RestResult<List<MerchantRequest>> merchantResult = managerMerchantApi.queryMerchantListByid(new ArrayList<Long>() {{
                add(goodsSpu.getMerchantId());
            }});
            setMerchantName(merchantResult.getData() == null || CollectionUtils.isEmpty(merchantResult.getData()) ? null : merchantResult.getData().get(0).getName());
            setCategoryName(goodsSpu.getCategoryName());
//            getMutexResultContext(Long.valueOf(skillGoodsRequest.getPromotionId()),);
            setMutexFlag(MutexFlagEnum.UN_MUTEX.getCode());
            setDeleteFlag(DeleteFlagEnum.UN_DELETE.getCode());
            setStoreId(goodsSpu.getStoreId());
            Long id = goodsSpu.getStoreId();
            Mestore mestore = mestoreService.queryByPrimaryKey(id);
            setStoreName(mestore.getStoreName());
        }};
    }

    /**
     * 获取互斥结果
     *
     * @param promotionId
     * @param goodsInfoResponseList
     * @return
     */
    private MutexResultContext getMutexResultContext(Long promotionId, List<ProductStoreInfo> goodsInfoResponseList) {
        final List<Long> productList = Lists.newArrayList();
        goodsInfoResponseList.forEach(spu -> {
//            productList.add(spu.getGoodsSpuInfo().getId());
            List<ProductStoreInfo> goodsSkuInfoList = spu.getChildren();
            goodsSkuInfoList.forEach(sku -> {
                productList.add(sku.getId());
            });
        });
        PromotionEntity promotionEntity = promotionEntityMapper.queryById(promotionId);
        return mutexService.doProcessMutex(
                new MutexModel()
                        .setPromotionId(promotionId)
                        .setPromType(promotionEntity.getPromType())
                        .setFrontPromotionType(promotionEntity.getFrontPromType())
                        .setProductList(productList)
        );
//        BaseActivity promotionEntity = baseActivityMapper.queryById(String.valueOf(promotionId));
//        return mutexService.doProcessMutex(
//                new MutexModel()
//                        .setPromotionId(promotionId)
//                        .setPromType(Integer.parseInt(promotionEntity.getPromType()))
//                        .setFrontPromotionType(Integer.parseInt(promotionEntity.getFrontPromType()))
//                        .setProductList(productList)
//        );
    }

    private ActivitySkillGoodsConfig spuValue(String promotionId, ProductStoreInfo goodsSpu, String timeId) {
        ActivitySkillGoodsConfig goodsConfig = new ActivitySkillGoodsConfig();
        goodsConfig.setTimeId(timeId);
        goodsConfig.setPromotionId(promotionId);
        goodsConfig.setDeleteFlag(false);
        goodsConfig.setMerchantId(goodsSpu.getMerchantId().toString());
        goodsConfig.setStoreId(goodsSpu.getStoreId().toString());
        goodsConfig.setSpuId("0");
        goodsConfig.setGoodsId(goodsSpu.getId().toString());
        goodsConfig.setGoodsName(goodsSpu.getChineseName());
        goodsConfig.setGoodsTypeName(goodsSpu.getCategoryName());
        goodsConfig.setReserveNum(goodsSpu.getAvailableStock().toString());
        goodsConfig.setGoodsPrice(goodsSpu.getSalePriceWithTax().toString());
        return goodsConfig;
    }

    private ActivitySkillGoodsConfig skuValue(String promotionId, GoodsQueryInfo goodsSku, String spuId, String timeId) {
        ActivitySkillGoodsConfig goodsConfig = new ActivitySkillGoodsConfig();
        goodsConfig.setPromotionId(promotionId);
        goodsConfig.setTimeId(timeId);
        goodsConfig.setDeleteFlag(false);
        goodsConfig.setMerchantId(goodsSku.getMerchantId().toString());
        goodsConfig.setStoreId(goodsSku.getStoreId().toString());
        goodsConfig.setSpuId(spuId);
        goodsConfig.setGoodsId(goodsSku.getId().toString());
        goodsConfig.setGoodsName(goodsSku.getGoodsName());
        goodsConfig.setGoodsTypeName(goodsSku.getGoodsCategory());
        goodsConfig.setReserveNum(goodsSku.getStock().toString());
        goodsConfig.setGoodsPrice(goodsSku.getSalePriceScope().toString());
        return goodsConfig;
    }

    private ActivitySkillGoodsConfig spuSingleValue(String promotionId, GoodsSpu goodsSpu, String timeId) {
        ActivitySkillGoodsConfig goodsConfig = new ActivitySkillGoodsConfig();
        goodsConfig.setTimeId(timeId);
        goodsConfig.setPromotionId(promotionId);
        goodsConfig.setDeleteFlag(false);
        goodsConfig.setMerchantId(goodsSpu.getMerchantId().toString());
        goodsConfig.setStoreId(goodsSpu.getStoreId().toString());
        goodsConfig.setSpuId("0");
        goodsConfig.setGoodsId(goodsSpu.getId().toString());
        goodsConfig.setGoodsName(goodsSpu.getGoodsName());
        goodsConfig.setGoodsTypeName(goodsSpu.getGoodsCategory());
        goodsConfig.setReserveNum(goodsSpu.getStock().toString());
        goodsConfig.setGoodsPrice(goodsSpu.getSalePriceScope());
        goodsConfig.setGoodsCode(goodsSpu.getThirdSpuId());
        return goodsConfig;
    }

    private ActivitySkillGoodsConfig skuSingleValue(String promotionId, GoodsSku goodsSku, String timeId) {
        ActivitySkillGoodsConfig goodsConfig = new ActivitySkillGoodsConfig();
        goodsConfig.setPromotionId(promotionId);
        goodsConfig.setTimeId(timeId);
        goodsConfig.setDeleteFlag(false);
        goodsConfig.setMerchantId(goodsSku.getMerchantId().toString());
        goodsConfig.setStoreId(goodsSku.getStoreId().toString());
        goodsConfig.setSpuId(goodsSku.getGoodsSpuId());
        goodsConfig.setGoodsId(goodsSku.getId().toString());
        goodsConfig.setGoodsName(goodsSku.getGoodsName());
        goodsConfig.setGoodsTypeName(goodsSku.getGoodsCategory());
        goodsConfig.setReserveNum(goodsSku.getStock().toString());
        goodsConfig.setGoodsPrice(goodsSku.getSalePrice().toString());
        goodsConfig.setGoodsCode(goodsSku.getThirdSkuId());
        return goodsConfig;
    }

    @Override
    public RestResult<Boolean> deleteGoods(SkillGoodsDeleteRequest skillGoodsDeleteRequest) {

        PromotionMerchantProductEntity productEntity = promotionMerchantProductEntityMapper.query(new PromotionMerchantProductEntity() {{
            setPromotionId(Long.valueOf(skillGoodsDeleteRequest.getPromotionId()));
            setSkillTimeId(skillGoodsDeleteRequest.getTimeId());
            setMpId(Long.valueOf(skillGoodsDeleteRequest.getGoodsId()));
            setDeleteFlag(DeleteFlagEnum.UN_DELETE.getCode());
        }});

        //是否存在未删除的互斥商品
        AtomicBoolean mutexFlag = new AtomicBoolean(false);
        if (TypeOfProductEnum.GOODS_SPU.getCode().equals(productEntity.getTypeOfProduct())) {
            //删除下级的sku
            List<PromotionMerchantProductEntity> productEntityList = promotionMerchantProductEntityMapper.findAll(new PromotionMerchantProductEntity() {{
                setDeleteFlag(DeleteFlagEnum.UN_DELETE.getCode());
                setMpParentId(productEntity.getMpId());
                setPromotionId(Long.valueOf(skillGoodsDeleteRequest.getPromotionId()));
                setSkillTimeId(skillGoodsDeleteRequest.getTimeId());
            }});
            productEntityList.forEach(product -> {
                if (MutexFlagEnum.MUTEX.getCode().equals(product.getMutexFlag()) && DeleteFlagEnum.UN_DELETE.getCode().equals(product.getDeleteFlag())) {
                    mutexFlag.set(true);
                } else {
                    promotionMerchantProductEntityMapper.update(new PromotionMerchantProductEntity() {{
                        setId(product.getId());
                        setDeleteFlag(DeleteFlagEnum.DELETE.getCode());
                    }});
                }
            });
        } else {
            //如果是sku查询是否删除所有sku
            List<PromotionMerchantProductEntity> productList = promotionMerchantProductEntityMapper.findAll(new PromotionMerchantProductEntity() {{
                setDeleteFlag(DeleteFlagEnum.UN_DELETE.getCode());
                setMpParentId(productEntity.getMpParentId());
                setPromotionId(Long.valueOf(skillGoodsDeleteRequest.getPromotionId()));
                setSkillTimeId(skillGoodsDeleteRequest.getTimeId());
            }});
            if (CollectionUtils.isEmpty(productList)) {
                //删除spu
                promotionMerchantProductEntityMapper.deleteEntityByPromotionIdAndMpIdAndTimeId(Long.valueOf(skillGoodsDeleteRequest.getPromotionId()),
                        productEntity.getMpParentId().toString(), skillGoodsDeleteRequest.getTimeId());
            }
        }
        if (!mutexFlag.get()) {
            promotionMerchantProductEntityMapper.deleteEntityByPromotionIdAndMpIdAndTimeId(Long.valueOf(skillGoodsDeleteRequest.getPromotionId()),
                    skillGoodsDeleteRequest.getGoodsId(), skillGoodsDeleteRequest.getTimeId());
        }
        return RestResult.success(false);
    }

    @Override
    public RestResult<Boolean> deleteBatchGoods(SkillBatchDeleteRequest skillBatchDeleteRequest) {
        if (CollectionUtils.isEmpty(skillBatchDeleteRequest.getGoodsId())) {
            return RestResult.success(true);
        }
        skillBatchDeleteRequest.getGoodsId().stream().forEach(temp -> {
            long flag = activitySkillGoodsConfigService.deleteByPromotionIdAndGoodsId(skillBatchDeleteRequest.getPromotionId(),
                    temp, skillBatchDeleteRequest.getTimeId());
        });
        return RestResult.success(true);
    }

    @Override
    public RestResult<SkillGoodsQueryResponse> queryGoodsId(SkillDeleteTimeOfDateRequest skillDeleteTimeOfDateRequest) {
        SkillGoodsQueryResponse response = new SkillGoodsQueryResponse();
        response.setPromotionId(skillDeleteTimeOfDateRequest.getPromotionId());
        if (skillDeleteTimeOfDateRequest.getStart() == null) {
            skillDeleteTimeOfDateRequest.setStart(1);
        }
        if (skillDeleteTimeOfDateRequest.getLimit() == null) {
            skillDeleteTimeOfDateRequest.setLimit(10);
        }
        Pagination pagination = Pagination.build(skillDeleteTimeOfDateRequest.getStart(), skillDeleteTimeOfDateRequest.getLimit());
        List<SkillGoodsInfo> goodsInfoList = new ArrayList<>();
        //查询当前时间段的商品列表 分页
        List<PromotionMerchantProductEntity> productEntityList = promotionMerchantProductEntityMapper.findMutexOfPageV2(new PromotionMerchantProductEntity() {{
            setPromotionId(Long.valueOf(skillDeleteTimeOfDateRequest.getPromotionId()));
            setSkillTimeId(skillDeleteTimeOfDateRequest.getSkillTimeId());
            setDeleteFlag(DeleteFlagEnum.UN_DELETE.getCode());
            setTypeOfProduct(TypeOfProductEnum.GOODS_SPU.getCode());
            setMutexFlag(skillDeleteTimeOfDateRequest.getMutexFlag());
            if (skillDeleteTimeOfDateRequest.getQueryGoodsReuqest() != null) {
                if (skillDeleteTimeOfDateRequest.getQueryGoodsReuqest().getStoreId() != null) {
                    setStoreId(Long.valueOf(skillDeleteTimeOfDateRequest.getQueryGoodsReuqest().getStoreId()));
                }
                setMpCode(skillDeleteTimeOfDateRequest.getQueryGoodsReuqest().getGoodsCode());
                setMpName(skillDeleteTimeOfDateRequest.getQueryGoodsReuqest().getGoodsName());
                setCategoryName(skillDeleteTimeOfDateRequest.getQueryGoodsReuqest().getGoodsType());
            }
        }}, pagination);

        int count = promotionMerchantProductEntityMapper.countMutexOfPageV2(new PromotionMerchantProductEntity() {{
            setPromotionId(Long.valueOf(skillDeleteTimeOfDateRequest.getPromotionId()));
            setSkillTimeId(skillDeleteTimeOfDateRequest.getSkillTimeId());
            setDeleteFlag(DeleteFlagEnum.UN_DELETE.getCode());
            setTypeOfProduct(TypeOfProductEnum.GOODS_SPU.getCode());
            setMutexFlag(skillDeleteTimeOfDateRequest.getMutexFlag());
            if (skillDeleteTimeOfDateRequest.getQueryGoodsReuqest() != null) {
                if (skillDeleteTimeOfDateRequest.getQueryGoodsReuqest().getStoreId() != null) {
                    setStoreId(Long.valueOf(skillDeleteTimeOfDateRequest.getQueryGoodsReuqest().getStoreId()));
                }
                setMpCode(skillDeleteTimeOfDateRequest.getQueryGoodsReuqest().getGoodsCode());
                setMpName(skillDeleteTimeOfDateRequest.getQueryGoodsReuqest().getGoodsName());
                setCategoryName(skillDeleteTimeOfDateRequest.getQueryGoodsReuqest().getGoodsType());
            }
        }});

        productEntityList.stream().forEach(promotionMerchantProductEntity -> {

            SkillGoodsInfo skillGoodsInfo = new SkillGoodsInfo();
            skillGoodsInfo.setDeptShare(promotionMerchantProductEntity.getDeptShare());
            skillGoodsInfo.setMerchantShare(promotionMerchantProductEntity.getMerchantShare());
            skillGoodsInfo.setId(promotionMerchantProductEntity.getId());
            skillGoodsInfo.setMerchantId(promotionMerchantProductEntity.getMerchantId().toString());
            skillGoodsInfo.setMerchantName(promotionMerchantProductEntity.getMerchantName());
            skillGoodsInfo.setStoreId(promotionMerchantProductEntity.getStoreId().toString());
            skillGoodsInfo.setStoreName(promotionMerchantProductEntity.getStoreName());
            skillGoodsInfo.setGoodsId(promotionMerchantProductEntity.getMpId().toString());
            skillGoodsInfo.setGoodsCode(promotionMerchantProductEntity.getMpCode());
            skillGoodsInfo.setGoodsName(promotionMerchantProductEntity.getMpName());
            skillGoodsInfo.setGoodsTypeName(promotionMerchantProductEntity.getCategoryName());
            skillGoodsInfo.setTypeOfProduct(promotionMerchantProductEntity.getTypeOfProduct());
            skillGoodsInfo.setMpId(promotionMerchantProductEntity.getMpId());
            skillGoodsInfo.setMpParentId(promotionMerchantProductEntity.getMpParentId());
            //查询商品价格和库存
//            GoodsSpu goodsSpu = goodsSpuMapper.queryByPrimaryKey(promotionMerchantProductEntity.getMpId());
            List<ProductStoreInfo> productStoreInfos = productListApi.queryProductBySpuList(new GoodsPageQueryRequest() {{
                setId(promotionMerchantProductEntity.getMpId());
            }});
            ProductStoreInfo goodsSpu = productStoreInfos.get(0);
            skillGoodsInfo.setGoodsPrice(goodsSpu.getSalePriceWithTax().toString());
            skillGoodsInfo.setReserveNum(goodsSpu.getAvailableStock().toString());
            skillGoodsInfo.setSkillPrice(promotionMerchantProductEntity.getPromPrice());
            skillGoodsInfo.setStoreChannelLimit(promotionMerchantProductEntity.getChannelStoreLimit() == null ? null : promotionMerchantProductEntity.getChannelStoreLimit().toString());
            skillGoodsInfo.setUserChannelLimit(promotionMerchantProductEntity.getChannelIndividualLimit() == null ? null : promotionMerchantProductEntity.getChannelIndividualLimit().toString());
            //查询SkuList
            List<PromotionMerchantProductEntity> skuList = promotionMerchantProductEntityMapper.findAll(new PromotionMerchantProductEntity() {{
                setDeleteFlag(DeleteFlagEnum.UN_DELETE.getCode());
                setSkillTimeId(skillDeleteTimeOfDateRequest.getSkillTimeId());
                setPromotionId(Long.valueOf(skillDeleteTimeOfDateRequest.getPromotionId()));
                setTypeOfProduct(TypeOfProductEnum.GOODS_SKU.getCode());
                setMpParentId(promotionMerchantProductEntity.getMpId());
                setMutexFlag(skillDeleteTimeOfDateRequest.getMutexFlag());
            }});
            List<SkillGoodsInfo> skillGoodsSkuInfoList = new ArrayList<>();
            skuList.stream().forEach(sku -> {
                SkillGoodsInfo skillGoodsSkuInfo = new SkillGoodsInfo();
                skillGoodsSkuInfo.setId(sku.getId());
                skillGoodsSkuInfo.setMerchantId(sku.getMerchantId().toString());
                skillGoodsSkuInfo.setMerchantName(sku.getMerchantName());
                skillGoodsSkuInfo.setStoreId(sku.getStoreId().toString());
                skillGoodsSkuInfo.setStoreName(sku.getStoreName());
                skillGoodsSkuInfo.setGoodsId(sku.getMpId().toString());
                skillGoodsSkuInfo.setGoodsCode(sku.getMpCode());
                skillGoodsSkuInfo.setGoodsName(sku.getMpName());
                skillGoodsSkuInfo.setGoodsTypeName(sku.getCategoryName());
                skillGoodsSkuInfo.setTypeOfProduct(sku.getTypeOfProduct());
                skillGoodsSkuInfo.setMpId(sku.getMpId());
                skillGoodsSkuInfo.setMpParentId(sku.getMpParentId());
                //查询商品价格和库存
//                GoodsSku goodsSku = goodsSkuMapper.queryByPrimaryKey(sku.getMpId());
                List<ProductStoreInfo> productStoreInfoSku = productListApi.queryProductBySpuList(new GoodsPageQueryRequest() {{
                    setId(sku.getMpId());
                }});
                ProductStoreInfo goodsSku = productStoreInfoSku.get(0);
                skillGoodsSkuInfo.setGoodsPrice(goodsSku.getSalePriceWithTax() == null ? null : goodsSku.getSalePriceWithTax().toString());
                skillGoodsSkuInfo.setReserveNum(goodsSku.getAvailableStock() == null ? null : goodsSku.getAvailableStock().toString());
                skillGoodsSkuInfo.setSkillPrice(sku.getPromPrice());
                skillGoodsSkuInfo.setStoreChannelLimit(sku.getChannelStoreLimit() == null ? null : sku.getChannelStoreLimit().toString());
                skillGoodsSkuInfo.setUserChannelLimit(sku.getChannelIndividualLimit() == null ? null : sku.getChannelIndividualLimit().toString());
                skillGoodsSkuInfoList.add(skillGoodsSkuInfo);
            });
            skillGoodsInfo.setChildren(skillGoodsSkuInfoList);
            goodsInfoList.add(skillGoodsInfo);
        });

        int skuTotal = promotionMerchantProductEntityMapper.countOfPage(new PromotionMerchantProductEntity() {{
            setDeleteFlag(DeleteFlagEnum.UN_DELETE.getCode());
            setSkillTimeId(skillDeleteTimeOfDateRequest.getSkillTimeId());
            setPromotionId(Long.valueOf(skillDeleteTimeOfDateRequest.getPromotionId()));
            setMutexFlag(skillDeleteTimeOfDateRequest.getMutexFlag());
            setTypeOfProduct(TypeOfProductEnum.GOODS_SKU.getCode());
        }});

        response.setSkillGoodsTimeResponseList(new ArrayList<SkillGoodsTimeResponse>() {{
            add(new SkillGoodsTimeResponse() {{
                setGoodsInfoList(goodsInfoList);
                setTotal(Long.valueOf(count));
                setSkuTotal(Long.valueOf(skuTotal));
            }});
        }});
        return RestResult.success(response);
    }

    @Override
    public RestResult<PageResult<SkillConfigQueryResponse>> querySkillConfigPage(SkillConfigQueryPageRequest request) {
        PageResult pageResult = new PageResult();
        BaseActivity activity = new BaseActivity();
        BeanUtils.copyProperties(request, activity);
        activity.setDeleteFlag(0);
        activity.setCreatorName(request.getCreatorNameForSearch());
        activity.setDeptType(request.getAdminOperate().getDeptType().getCode());
        Page page = new Page();
        page.setStart(request.getStart());
        page.setLimit(request.getLimit());

        PageResult<BaseActivity> result = baseActivityService.querySkillPage(activity,
                page,
                request.getMerchantId(),
                request.getStoreId());
        pageResult.setTotal(result.getTotal());

        if (CollectionUtils.isEmpty(result.getRows())) {
            pageResult.setRows(new ArrayList());
            return RestResult.success(pageResult);
        }

        List<SkillConfigQueryResponse> responsesList = getSkillConfigQueryResponseList(result.getRows(), request.getAdminOperate());
        pageResult.setRows(responsesList);
        return RestResult.success(pageResult);
    }

    @Override
    public RestResult<Boolean> updateSkillConfig(SkillConfigUpdateaRequest skillConfigUpdateaRequest) {
        RestResult<Boolean> result = RestResult.success(true);
        if (skillConfigUpdateaRequest.getStartTime() != null && skillConfigUpdateaRequest.getStartTime().getTime() < new Date().getTime()) {
            result.setCode("5000");
            result.setData(false);
            result.setMsg("活动开始时间不能小于当前时间!");
            return result;
        }
        PromotionEntity promotionEntity = new PromotionEntity();
        BeanUtils.copyProperties(skillConfigUpdateaRequest, promotionEntity);
        promotionEntity.setLabelId(StringUtils.isEmpty(skillConfigUpdateaRequest.getLabel()) ? null : Long.valueOf(skillConfigUpdateaRequest.getLabel()));
        promotionEntity.setParcelsFlag(StringUtils.isEmpty(skillConfigUpdateaRequest.getParcelsFlag()) ? null : Integer.valueOf(skillConfigUpdateaRequest.getParcelsFlag()));
        promotionEntity.setId(Long.valueOf(skillConfigUpdateaRequest.getPromotionId()));
//        long flag = baseActivityService.update(activity);
        promotionEntityMapper.update(promotionEntity);
        SkillActivityConfig skillActivityConfig = setSkillActivityConfig(skillConfigUpdateaRequest, skillConfigUpdateaRequest.getPromotionId());
        update(skillActivityConfig);

        MemberGradeInfoRequest memberGradeInfoRequest = new MemberGradeInfoRequest();
        memberGradeInfoRequest.setPromotionId(promotionEntity.getId().toString());
        memberGradeInfoRequest.setPromotionCode(promotionEntity.getPromotionCode());
        memberGradeInfoRequest.setPromType(PromotionTypeEnum.SECKILL.getCode());
        memberGradeInfoRequest.setFrontPromType(30);//先随便定义一个值吧
        memberGradeInfoRequest.setPromotionMemberGradeList(skillConfigUpdateaRequest.getPromotionMemberGradeList());
        promotionMemberGradeService.updateMemberGrade(memberGradeInfoRequest);

        insertBatchTime(skillConfigUpdateaRequest.getTimeInfoList(), skillConfigUpdateaRequest.getPromotionId());
        updateBatchTime(skillConfigUpdateaRequest);
        return result;
    }

    private void updateBatchTime(SkillConfigUpdateaRequest skillConfigUpdateaRequest) {
        if (CollectionUtils.isEmpty(skillConfigUpdateaRequest.getUpdateTimeInfoList())) {
            return;
        }
        skillConfigUpdateaRequest.getUpdateTimeInfoList().stream().forEach(temp -> {
            skillActivityTimeConfigService.updateTimeByPromotionId(temp.getStartTimeOfDate(),
                    temp.getEndTimeOfDate(),
                    skillConfigUpdateaRequest.getPromotionId(),
                    temp.getSkillTimeId());
        });
    }

    @Override
    public RestResult<String> copySkillConfig(PromotionIdRequest promotionIdRequest, boolean templateFalg) {
        List<CompletableFuture<Integer>> completableFutures = new ArrayList<>();
        //复制秒杀
        PromotionEntity promotionEntity = promotionEntityMapper.queryById(Long.valueOf(promotionIdRequest.getPromotionId()));

        String oldPromotionCode = promotionEntity.getPromotionCode();

        if (promotionEntity == null) {
            return RestResult.error("9999", "promotionId查不到数据");
        }
        Date now = new Date();
        promotionEntity.setCreateTime(now);
        promotionEntity.setUpdateTime(now);
        promotionEntity.setDeleteFlag(DeleteFlagEnum.UN_DELETE.getCode());
        promotionEntity.setPromotionCode(IDUtils.GenerateBillNo(promotionEntity.getFrontPromType().toString()));
        promotionEntity.setCreator(promotionEntity.getCreator());
        promotionEntity.setCreatorName(promotionEntity.getCreatorName());
        promotionEntity.setUpdator(promotionEntity.getCreator());
        promotionEntity.setUpdatorName(promotionEntity.getCreatorName());
        if (!templateFalg) {
            promotionEntity.setStatus(com.jic.market.common.enums.PromotionStatusEnum.DRAFT.getCode());
        } else {
            promotionEntity.setStatus(com.jic.market.common.enums.PromotionStatusEnum.TEMPLATE.getCode());
        }
        promotionEntity.setId(null);
        promotionEntityMapper.insert(promotionEntity);
        String newPromotionId = promotionEntity.getId().toString();

        CompletableFuture<Integer> configCompletableFuture = CompletableFuture.supplyAsync(() -> {
            try {
                long start = System.currentTimeMillis();
                copySkillActivityConfig(promotionIdRequest, newPromotionId);
                log.info("copySkillConfig success copySkillActivityConfig cost = {}", System.currentTimeMillis() - start);
            } catch (Exception e) {
                log.error("copySkillConfig copySkillActivityConfig error", e);
            }
            return 1;
        }, executorServiceR);
        completableFutures.add(configCompletableFuture);

//        if (!copySkillActivityConfig(promotionIdRequest, newPromotionId)) {
//            return RestResult.error("9999", "复制秒杀基础配置出错");
//        }

        CompletableFuture<Integer> merchantGradeRuleCompletableFuture = CompletableFuture.supplyAsync(() -> {
            try {
                long start = System.currentTimeMillis();
                copyMerchantAndStore(promotionIdRequest, newPromotionId);
                log.info("copySkillConfig success copyMerchantAndStore cost = {}", System.currentTimeMillis() - start);
            } catch (Exception e) {
                log.error("copySkillConfig copyMerchantAndStore error", e);
            }
            return 1;
        }, executorServiceR);
        completableFutures.add(merchantGradeRuleCompletableFuture);

//        if (!copyMerchantAndStore(promotionIdRequest, newPromotionId)) {
//            return RestResult.error("9999", "复制秒杀商家/店铺配置出错");
//        }

        CompletableFuture<Integer> timeRuleCompletableFuture = CompletableFuture.supplyAsync(() -> {
            try {
                long start = System.currentTimeMillis();
                copyTime(promotionIdRequest, newPromotionId);
                log.info("copySkillConfig success copyTime cost = {}", System.currentTimeMillis() - start);
            } catch (Exception e) {
                log.error("copySkillConfig copyTime error", e);
            }
            return 1;
        }, executorServiceR);
        completableFutures.add(timeRuleCompletableFuture);

//        if (!copyTime(promotionIdRequest, newPromotionId)) {
//            return RestResult.error("9999", "复制秒杀配置时间出错");
//        }
        CompletableFuture<Integer> goodsCompletableFuture = CompletableFuture.supplyAsync(() -> {
            try {
                long start = System.currentTimeMillis();
                copyGoods(promotionIdRequest, newPromotionId);
                log.info("copySkillConfig success copyGoods cost = {}", System.currentTimeMillis() - start);
            } catch (Exception e) {
                log.error("copySkillConfig copyGoods error", e);
            }
            return 1;
        }, executorServiceR);
        completableFutures.add(goodsCompletableFuture);
//        if (!copyGoods(promotionIdRequest, newPromotionId)) {
//            return RestResult.error("9999", "复制秒杀商品配置出错");
//        }

        CompletableFuture<Integer> memberCompletableFuture = CompletableFuture.supplyAsync(() -> {
            try {
                long start = System.currentTimeMillis();
                promotionMemberGradeService.copyMemberGrade(oldPromotionCode, promotionEntity.getId().toString(), promotionEntity.getPromotionCode());
                ;
                log.info("copySkillConfig success copyMemberGrade cost = {}", System.currentTimeMillis() - start);
            } catch (Exception e) {
                log.error("copySkillConfig copyMemberGrade error", e);
            }
            return 1;
        }, executorServiceR);
        completableFutures.add(memberCompletableFuture);
        CompletableFuture.allOf(completableFutures.toArray(new CompletableFuture[completableFutures.size()])).join();

        return RestResult.success(newPromotionId);
    }

    @Override
    public RestResult<Boolean> colseSkillConfig(PromotionIdRequest promotionIdRequest) {
//        long flag = baseActivityService.updateStatusByPromotionId(promotionIdRequest.getPromotionId(),
//                PromotionStatusEnum.CLOSED.getCode().toString());
        PromotionEntity promotionEntity = promotionEntityMapper.queryById(Long.valueOf(promotionIdRequest.getPromotionId()));
        if (promotionEntity != null) {
            promotionEntity.setStatus(com.jic.market.common.enums.PromotionStatusEnum.CLOSED.getCode());
            promotionEntityMapper.update(promotionEntity);
        }
        return RestResult.success(true);
    }

    @Override
    public RestResult<Boolean> deleteSkillConfig(PromotionIdRequest promotionIdRequest) {
        promotionEntityMapper.update(new PromotionEntity() {{
            setDeleteFlag(DeleteFlagEnum.DELETE.getCode());
            setId(Long.valueOf(promotionIdRequest.getPromotionId()));
        }});
        skillActivityConfigMapper.delete(promotionIdRequest.getPromotionId());
        promotionMerchantEntityMapper.deleteByPromotionId(Long.valueOf(promotionIdRequest.getPromotionId()));
        skillActivityTimeConfigService.delete(promotionIdRequest.getPromotionId());
        promotionMerchantProductEntityMapper.deleteEntityByPromotionId(Long.valueOf(promotionIdRequest.getPromotionId()));
        promotionMutexService.deleteByPromotionIdAndPromType(Long.valueOf(promotionIdRequest.getPromotionId()), PromotionTypeEnum.SECKILL.getCode());
        return RestResult.success(true);
    }

    @Override
    public RestResult<Boolean> deleteSkillMerchant(MerchantDeleteRequest merchantDeleteRequest) {
        promotionMerchantEntityMapper.deleteMerchantByPromotionId(Long.valueOf(merchantDeleteRequest.getMerchantId()), Long.valueOf(merchantDeleteRequest.getPromotionId()));
        promotionMerchantEntityMapper.deletStoreByMerchantIdAndPromotionId(Long.valueOf(merchantDeleteRequest.getMerchantId()), Long.valueOf(merchantDeleteRequest.getPromotionId()));
        promotionMerchantProductEntityMapper.deleteEntityByPromotionIdAndMerchantId(Long.valueOf(merchantDeleteRequest.getMerchantId()), Long.valueOf(merchantDeleteRequest.getPromotionId()));
        return RestResult.success(true);
    }

    @Override
    public RestResult<Boolean> deleteSkillStore(StoreDeleteRequest storeDeleteRequest) {
        promotionMerchantEntityMapper.deleteStoreByPromotionId(Long.valueOf(storeDeleteRequest.getStoreId()), Long.valueOf(storeDeleteRequest.getPromotionId()));
        promotionMerchantProductEntityMapper.deleteEntityByPromotionIdAndStoreId(Long.valueOf(storeDeleteRequest.getStoreId()), Long.valueOf(storeDeleteRequest.getPromotionId()));
        return RestResult.success(true);
    }

    @Override
    public RestResult<Boolean> deleteTimeOfDate(SkillDeleteTimeOfDateRequest skillDeleteTimeOfDateRequest) {
        skillActivityTimeConfigService.deleteByPromotionIdAndTimeId(skillDeleteTimeOfDateRequest.getPromotionId(),
                skillDeleteTimeOfDateRequest.getSkillTimeId());
        activitySkillGoodsConfigService.deleteGoodsByPromotionIdAndTimeId(skillDeleteTimeOfDateRequest.getPromotionId(),
                skillDeleteTimeOfDateRequest.getSkillTimeId());
        return RestResult.success(true);
    }

    @Override
    public RestResult<Boolean> checkCoupon(SkillCheckRequest skillCheckRequest) {
        RestResult<Boolean> restResult = RestResult.success(true);
        //提交审核校验该活动下是否存在商家、店铺、商品
        //获取当前登录用户有权限的商家列表
//        List<Long> merchantIds = Collections.emptyList();
//        if (CollectionUtils.isNotEmpty(skillCheckRequest.getAdminOperate().getMerchantIds())) {
//            merchantIds = skillCheckRequest.getAdminOperate().getMerchantIds();
//        }
//        //查询活动下商家
//        Long total = promotionMerchantEntityMapper.queryByPromotionIdTotal(Long.valueOf(skillCheckRequest.getPromotionId()),
//                merchantIds, null, MerchantTypeEnum.MERCHANT.getCode());
//
//        if (total == 0L) {
//            restResult.setCode("5000");
//            restResult.setData(false);
//            restResult.setMsg("该活动下所选商家为空，请先添加商家！");
//            return restResult;
//        }
//        //获取当前登录用户有权限的店铺列表
//        List<Long> storeIds = Collections.emptyList();
//        if (org.apache.commons.collections.CollectionUtils.isNotEmpty(skillCheckRequest.getAdminOperate().getStoreIds())) {
//            storeIds = skillCheckRequest.getAdminOperate().getStoreIds();
//        }
//        //查询活动下店铺
//        Long storeTotal = promotionMerchantEntityMapper.queryByPromotionIdTotal(Long.valueOf(skillCheckRequest.getPromotionId()), null,
//                storeIds, MerchantTypeEnum.STORE.getCode());
//        if (storeTotal == 0L) {
//            restResult.setCode("5000");
//            restResult.setData(false);
//            restResult.setMsg("该活动下所选店铺为空，请先添加店铺！");
//            return restResult;
//        }
        //查询活动下商品
        List<PromotionMerchantProductEntity> productEntityList = promotionMerchantProductEntityMapper.findAll(new PromotionMerchantProductEntity() {{
            setPromotionId(Long.valueOf(skillCheckRequest.getPromotionId()));
        }});
        int goodsTotal = productEntityList.size();
        if (goodsTotal == 0) {
            restResult.setCode("5000");
            restResult.setData(false);
            restResult.setMsg("该活动下所选商品为空，请先添加商品！");
            return restResult;
        }

        promotionEntityMapper.update(new PromotionEntity() {{
            setId(Long.valueOf(skillCheckRequest.getPromotionId()));
            setAuditRemark(skillCheckRequest.getCheckRemark());
            setStatus(Integer.valueOf(skillCheckRequest.getUpdateStatus()));
        }});
//        if (skillCheckRequest.getUpdateStatus() != null && skillCheckRequest.getUpdateStatus().equals("11")) {//审核
//            TellAddAllocationRequest tellAddAllocationRequest = new TellAddAllocationRequest();
//            tellAddAllocationRequest.setPromotionId(skillCheckRequest.getPromotionId() + "");
//            tellAddAllocationRequest.setPromType(promotionEntityMapper.queryById(Long.parseLong(skillCheckRequest.getPromotionId())).getPromType());
//            allocationLogicService.addAllocation(tellAddAllocationRequest);
//        }
        return restResult;
    }

    @Override
    public RestResult<Boolean> updateImagesUrl(SkillImagesUrlUpdateRequest skillImagesUrlUpdateRequest) {
        String imagesUrl = "";
        List<String> imagesUrls = skillImagesUrlUpdateRequest.getImagesUrls();
        for (String url : imagesUrls) {
            if (!StringUtils.isEmpty(url)) {
                imagesUrl = url + "," + imagesUrl;
            }
        }
        skillActivityConfigMapper.updateImagesUrlByPromotionId(skillImagesUrlUpdateRequest.getPromotionId(),
                imagesUrl);
        return RestResult.success(true);
    }

    @Override
    public RestResult<Boolean> updateGoodsConfig(SkillGoodsRequest skillGoodsRequest) {
        if (CollectionUtils.isEmpty(skillGoodsRequest.getGoodsInfoList())) {
            return RestResult.success(true);
        }
        skillGoodsRequest.getGoodsInfoList().stream().forEach(temp -> {
            PromotionMerchantProductEntity productEntity = new PromotionMerchantProductEntity();
            BeanUtils.copyProperties(temp, productEntity);
            productEntity.setId(Long.valueOf(temp.getGoodsId()));
            productEntity.setPromotionId(Long.valueOf(skillGoodsRequest.getPromotionId()));
            productEntity.setSkillTimeId(skillGoodsRequest.getSkillTimeId());
            productEntity.setChannelIndividualLimit(temp.getUserChannelLimit() == null || StringUtils.isEmpty(temp.getUserChannelLimit()) ? null : Long.valueOf(temp.getUserChannelLimit()));
            productEntity.setChannelStoreLimit(temp.getStoreChannelLimit() == null || StringUtils.isEmpty(temp.getStoreChannelLimit()) ? null : Long.valueOf(temp.getStoreChannelLimit()));
            productEntity.setPromPrice(temp.getSkillPrice() == null ? null : temp.getSkillPrice());
            promotionMerchantProductEntityMapper.updateBySkillTimeId(productEntity);
        });
        return RestResult.success(true);
    }

    @Override
    public RestResult<List<SkillConfigQueryResponse>> querySkillConfigList(SkillBatchQueryRequest skillBatchQueryRequest) {
        if (CollectionUtils.isEmpty(skillBatchQueryRequest.getPromotionIdList())) {
            return RestResult.success(new ArrayList<>());
        }
        List<SkillConfigQueryResponse> responseList = new ArrayList<>();
        skillBatchQueryRequest.getPromotionIdList().stream().forEach(promotionId -> {
            PromotionIdRequest promotionIdRequest = new PromotionIdRequest();
            promotionIdRequest.setPromotionId(promotionId);
            promotionIdRequest.setAdminOperate(skillBatchQueryRequest.getAdminOperate());
            RestResult<SkillConfigQueryResponse> result = querySkillConfig(promotionIdRequest);
            if (RestResult.checkIsSuccess(result) && result.getData() != null) {
                responseList.add(result.getData());
            }
        });

        return RestResult.success(responseList);
    }

    @Override
    public RestResult<String> saveTemplate(CouponTemplatRequest couponTemplatRequest) {
        PromotionIdRequest promotionIdRequest = new PromotionIdRequest();
        promotionIdRequest.setPromotionId(couponTemplatRequest.getPromotionId());
        RestResult<String> result = copySkillConfig(promotionIdRequest, true);
        if (!RestResult.checkIsSuccess(result)) {
            return result;
        }
        Long templateId = promotionTemplateService.saveTemplate(() -> {
            // 复制配置信息
            PromotionTemplateService.CopyResult copyResult = new PromotionTemplateService.CopyResult();
            copyResult.setPromotionId(result.getData());
            copyResult.setPromType(PromotionTypeEnum.SECKILL);
            copyResult.setTemplateName(couponTemplatRequest.getTemplateName());
            copyResult.setAdminOperate(couponTemplatRequest.getAdminOperate());
            return copyResult;
        });
        return RestResult.success(templateId == null ? "" : Long.toString(templateId));
    }

    @Override
    public RestResult<Boolean> addAllGoodsConfig(SkillGoodsIdsRequest skillGoodsRequest) {
        //删除已经存在的商品
        promotionMerchantProductEntityMapper.deleteEntityByPromotionIdAndTimeId(Long.valueOf(skillGoodsRequest.getPromotionId()), skillGoodsRequest.getSkillTimeId());

        //查询活动下的店铺ids
        List<Long> storeIdsByPromotionId = promotionMerchantEntityMapper.getStoreIdsByPromotionId(skillGoodsRequest.getPromotionId());

        //查询当前店铺下所有商品
        GoodsPageQueryRequest goodsPageQueryRequest = new GoodsPageQueryRequest();
        goodsPageQueryRequest.setStoreIds(storeIdsByPromotionId);
        List<ProductStoreInfo> data = productListApi.queryProductByStoreId(goodsPageQueryRequest);
//        RestResult<List<GoodsPageQueryResponse>> listRestResult = goodsQueryService.queryByAllCondition(goodsPageQueryRequest);
//        List<GoodsPageQueryResponse> data = listRestResult.getData();
        data.forEach(goodsPageQueryResponse -> {
            //插入spu
            ProductStoreInfo goodsInfo = goodsPageQueryResponse;
//            GoodsSpu goodsSpu = new GoodsSpu();
//            BeanUtils.copyProperties(goodsInfo,goodsSpu);
//            goodsSpu.setThirdSpuId(goodsInfo.getCode());
//
//            GoodsSkuQueryRequest goodsSkuQueryRequest = new GoodsSkuQueryRequest();
//            goodsSkuQueryRequest.setGoodsSpuIds(new ArrayList<Long>(){{
//                add(goodsSpu.getId());
//            }});
            List<ProductStoreInfo> goodsInfoResponseList = goodsInfo.getChildren();
//            RestResult<List<QueryGoodsInfoResponse>> goodsSpuRest = goodsQueryService.queryByGoodsSpuIds(goodsSkuQueryRequest);
//            List<QueryGoodsInfoResponse> goodsInfoResponseList = goodsSpuRest.getData();
//            if(CollectionUtils.isEmpty(goodsInfoResponseList)){
//                return;
//            }
            final MutexResultContext mutexResultContext = getMutexResultContext(Long.valueOf(skillGoodsRequest.getPromotionId()), goodsInfoResponseList);
            final Set<Long> mutexList = mutexResultContext.getMutexList();
            //final Set<Long> noMutexList = mutexResultContext.getNoMutexList();
            final Map<Long, Set<MutexProductEntity>> mutexPromotionProducts = mutexResultContext.getMutexPromotionProducts();

            PromotionMerchantProductEntity productEntity = spuValueNew(skillGoodsRequest, goodsInfo, mutexList);
            promotionMerchantProductEntityMapper.insert(productEntity);
//            List<GoodsSku> goodsSkuList = new ArrayList<>();
//            goodsInfoResponseList.forEach(skuInfo->{
//                GoodsSku goodsSku = new GoodsSku();
//                BeanUtils.copyProperties(skuInfo,goodsSku);
//                goodsSku.setThirdSkuId(skuInfo.getCode());
//                goodsSkuList.add(goodsSku);
//            });
            List<PromotionMerchantProductEntity> productEntityList = skuValueNew(skillGoodsRequest, goodsInfoResponseList, mutexList);
            promotionMerchantProductEntityMapper.insertBatch(productEntityList);

            productEntityList.add(productEntity);
            //插入互斥表
            mutexPromotionProducts.entrySet().forEach(e -> {
                Set<MutexProductEntity> mutexProductEntitySet = e.getValue();
                List<PromotionMerchantProductEntity> collect = productEntityList.stream().filter(a -> a.getMpId().equals(e.getKey())).collect(Collectors.toList());
                if (CollectionUtils.isEmpty(collect)) {
                    return;
                }
                promotionMutexService.deleteByPromotionProductId(collect.get(0).getId());
                mutexProductEntitySet.forEach(m -> {
                    promotionMutexService.insert(
                            new PromotionMutex()
                                    .setPromotionId(m.getPromotionId())
                                    .setPromType(m.getPromType())
                                    .setDeleteFlag(DeleteFlagEnum.UN_DELETE.getCode())
                                    .setPromotionMerchantProductId(collect.get(0).getId())
                                    .setCreator(skillGoodsRequest.getAdminOperate().getOperator())
                                    .setCreatorName(skillGoodsRequest.getAdminOperate().getOperateName())
                                    .setUpdator(skillGoodsRequest.getAdminOperate().getOperator())
                                    .setUpdatorName(skillGoodsRequest.getAdminOperate().getOperateName())
                    );
                });
            });
        });
        return RestResult.success(true);
    }

    private boolean copyGoods(PromotionIdRequest promotionIdRequest, String newPromotionId) {
        List<String> timeIdList = skillActivityTimeConfigService.queryTimeIdByPromotionId(promotionIdRequest.getPromotionId());
        if (CollectionUtils.isEmpty(timeIdList)) {
            return true;
        }
        timeIdList.stream().forEach(temp -> {
            List<PromotionMerchantProductEntity> configList = promotionMerchantProductEntityMapper.findAll(new PromotionMerchantProductEntity() {{
                setDeleteFlag(DeleteFlagEnum.UN_DELETE.getCode());
                setPromotionId(Long.valueOf(promotionIdRequest.getPromotionId()));
                setSkillTimeId(temp);
            }});
            if (CollectionUtils.isNotEmpty(configList)) {
                configList.stream().forEach(goodTemplate -> {
                    goodTemplate.setPromotionId(Long.valueOf(newPromotionId));
                    String newTimeId = getNewTimeId(newPromotionId, new ActivitySkillGoodsConfig() {{
                        setTimeId(goodTemplate.getSkillTimeId());
                    }});
                    if (!StringUtils.isEmpty(newTimeId)) {
                        goodTemplate.setSkillTimeId(newTimeId);
                        //promotionMerchantProductEntityMapper.insert(goodTemplate);
                    }
                });
                promotionMerchantProductEntityMapper.insertBatchNew(configList);
            }
        });
        return true;
    }

    //TODO 此处有并发问题，时间太紧后期优化
    private String getNewTimeId(String newPromotionId, ActivitySkillGoodsConfig config) {
        SkillActivityTimeConfig oldConfig = skillActivityTimeConfigService.queryTimeConfigByPromotionIdAndTimeId(config.getPromotionId(), config.getTimeId());
        if (oldConfig == null) {
            return "";
        }
        String timeId = skillActivityTimeConfigService.queryTimeIdByPromotionIdAndDate(newPromotionId, oldConfig.getStartTimeOfDate(), oldConfig.getEndTimeOfDate());
        return timeId;
    }

    private boolean copyTime(PromotionIdRequest promotionIdRequest, String newPromotionId) {
        List<SkillActivityTimeConfig> timeConfigList = skillActivityTimeConfigService.queryByPromotionId(promotionIdRequest.getPromotionId());
        if (CollectionUtils.isEmpty(timeConfigList)) {
            return true;
        }
        timeConfigList.stream().forEach(temp -> {
            temp.setPromotionId(newPromotionId);
            temp.setTimeId(IDUtils.GenerateBillNo());
            //skillActivityTimeConfigService.insert(temp);
        });
        skillActivityTimeConfigService.insertBatch(timeConfigList);
        return true;
    }

    private boolean copyStore(PromotionIdRequest promotionIdRequest, String newPromotionId) {
        List<ActivityStoreConfig> storeConfigList = activityStoreConfigService.queryStoreByPromotionId(promotionIdRequest.getPromotionId(), null, null, Collections.emptyList(), null);
        if (CollectionUtils.isEmpty(storeConfigList)) {
            return true;
        }
        storeConfigList.stream().forEach(temp -> {
            temp.setPromotionId(newPromotionId);
            activityStoreConfigService.insert(temp);
        });
        return true;
    }

    private boolean copyMerchant(PromotionIdRequest promotionIdRequest, String newPromotionId) {
        List<ActivityMerchantConfig> merchantConfigList = activityMerchantConfigService.queryByPromotionId(promotionIdRequest.getPromotionId(), null, null, Collections.emptyList(), null);
        if (CollectionUtils.isEmpty(merchantConfigList)) {
            return true;
        }
        merchantConfigList.stream().forEach(temp -> {
            temp.setPromotionId(newPromotionId);
            activityMerchantConfigService.insert(temp);
        });
        return true;
    }

    private boolean copyMerchantAndStore(PromotionIdRequest promotionIdRequest, String newPromotionId) {
//        List<ActivityMerchantConfig> merchantConfigList = activityMerchantConfigService.queryByPromotionId(promotionIdRequest.getPromotionId(),null,null,Collections.emptyList());
        List<PromotionMerchantEntity> merchantEntityList = promotionMerchantEntityMapper.findAll(new PromotionMerchantEntity() {{
            setDeleteFlag(DeleteFlagEnum.UN_DELETE.getCode());
            setPromotionId(Long.valueOf(promotionIdRequest.getPromotionId()));
        }});
        if (CollectionUtils.isEmpty(merchantEntityList)) {
            return true;
        }
        merchantEntityList.stream().forEach(temp -> {
            temp.setPromotionId(Long.valueOf(newPromotionId));
            temp.setId(null);
            //promotionMerchantEntityMapper.insert(temp);
        });
        promotionMerchantEntityMapper.insertBatch(merchantEntityList);
        return true;
    }

    private boolean copySkillActivityConfig(PromotionIdRequest promotionIdRequest, String newPromotionId) {
        SkillActivityConfig config = skillActivityConfigMapper.queryByPromotionId(promotionIdRequest.getPromotionId());
        if (config == null) {
            return false;
        }
        config.setPromotionId(newPromotionId);
        long flag = insert(config);
        if (flag < 0) {
            return false;
        }
        return true;
    }

    private List<SkillConfigQueryResponse> getSkillConfigQueryResponseList(List<BaseActivity> configList, AdminOperate adminOperate) {
        List<SkillConfigQueryResponse> responsesList = new ArrayList<>();
        if (CollectionUtils.isEmpty(configList)) {
            return responsesList;
        }
        configList.stream().forEach(temp -> {
            SkillConfigQueryResponse response = new SkillConfigQueryResponse();
            BeanUtils.copyProperties(temp, response);
            response.setEditFlag(adminOperate.getDeptId().equals(Long.valueOf(temp.getDeptId())) ? true : false);
            response.setChannelCodes(getArrayList(temp.getChannelCodes()));
            responsesList.add(response);
        });
        return responsesList;
    }

    private List<String> getArrayList(String param) {
        if (StringUtils.isEmpty(param)) {
            return new ArrayList<>();
        }
        String[] str = param.split(",");
        List<String> stringList = Arrays.stream(str).collect(Collectors.toList());
        return stringList;
    }

    private List<SkillGoodsTimeResponse> getSkillGoodsTimeResponse(List<String> timeList, String promotionId) {
        List<SkillGoodsTimeResponse> skillGoodsTimeResponseList = new ArrayList<>();
        timeList.stream().forEach(temp -> {
            SkillGoodsTimeResponse timeResponse = new SkillGoodsTimeResponse();
            timeResponse.setSkillTimeId(temp);
            List<SkillGoodsInfo> goodsInfoList = getSkillGoodsInfoList(promotionId, temp);
            //过滤树
            //转换树状结构
            List<SkillGoodsInfo> restResponse = new ArrayList<>();
            for (SkillGoodsInfo dept : goodsInfoList) {
                if ("0".equals(dept.getSpuId())) {
                    restResponse.add(dept);
                }
            }
            findChildren(restResponse, goodsInfoList);

            timeResponse.setGoodsInfoList(restResponse);
            skillGoodsTimeResponseList.add(timeResponse);
        });
        return skillGoodsTimeResponseList;
    }

    private void findChildren(List<SkillGoodsInfo> sysDepts, List<SkillGoodsInfo> depts) {
        for (SkillGoodsInfo sysDept : sysDepts) {
            List<SkillGoodsInfo> children = new ArrayList<>();
            for (SkillGoodsInfo dept : depts) {
                if (sysDept.getGoodsId().equals(dept.getSpuId())) {
//                    sysDeptResponse.setParentName(sysDept.getDeptName());
//                    sysDeptResponse.setLevel(sysDept.getLevel()+1);
                    children.add(dept);
                }
            }
            sysDept.setChildren(children);
            findChildren(children, depts);
        }
    }


    private List<SkillGoodsInfo> getSkillGoodsInfoList(String promotionId, String timeId) {
        List<ActivitySkillGoodsConfig> configList = activitySkillGoodsConfigService.queryGoodsInfoByTimeId(promotionId, timeId, null, null);
        if (CollectionUtils.isEmpty(configList)) {
            return new ArrayList<>();
        } else {
            List<SkillGoodsInfo> goodsInfoList = new ArrayList<>();
            configList.stream().forEach(activitySkillGoodsConfig -> {

                RestResult<List<MerchantRequest>> listRestResult = managerMerchantApi.queryMerchantListByid(new ArrayList<Long>() {{
                    add(Long.valueOf(activitySkillGoodsConfig.getMerchantId()));
                }});
                SkillGoodsInfo goodsInfo = new SkillGoodsInfo();
                BeanUtils.copyProperties(activitySkillGoodsConfig, goodsInfo);

                goodsInfo.setMerchantName(listRestResult.getData().get(0).getName());
                //查询商品  商品库存 商品售价
                if (goodsInfo.getSpuId().equals("0")) {
                    //查询spu
//                    GoodsSpu goodsSpu = goodsSpuMapper.queryByPrimaryKey(Long.valueOf(goodsInfo.getGoodsId()));
                    List<ProductStoreInfo> productStoreInfos = productListApi.queryProductBySpuList(new GoodsPageQueryRequest() {{
                        setId(Long.valueOf(goodsInfo.getGoodsId()));
                    }});
                    ProductStoreInfo goodsSpu = productStoreInfos.get(0);
                    goodsInfo.setGoodsPrice(goodsSpu.getSalePriceWithTax().toString());
                    goodsInfo.setReserveNum(String.valueOf(goodsSpu.getAvailableStock()));
                } else {
                    //查询 sku
//                    GoodsSku goodsSku = goodsSkuMapper.queryByPrimaryKey(Long.valueOf(goodsInfo.getGoodsId()));
                    List<ProductStoreInfo> productStoreInfos = productListApi.queryProductBySpuList(new GoodsPageQueryRequest() {{
                        setId(Long.valueOf(goodsInfo.getGoodsId()));
                    }});
                    ProductStoreInfo goodsSku = productStoreInfos.get(0);
                    goodsInfo.setGoodsPrice(goodsSku.getSalePriceWithTax().toString());
                    goodsInfo.setReserveNum(String.valueOf(goodsSku.getAvailableStock()));
                }

                goodsInfoList.add(goodsInfo);
            });
            return goodsInfoList;
        }
    }

    private List<SkillTimeResponseInfo> getSkillTimeResponseInfoList(String promotionId) {
        List<SkillActivityTimeConfig> configList = skillActivityTimeConfigService.queryByPromotionId(promotionId);
        if (CollectionUtils.isEmpty(configList)) {
            return new ArrayList<>();
        }
        List<SkillTimeResponseInfo> responseInfoList = new ArrayList<>(configList.size());
        configList.stream().forEach(temp -> {
            SkillTimeResponseInfo responseInfo = new SkillTimeResponseInfo();
            responseInfo.setEndTimeOfDate(temp.getEndTimeOfDate());
            responseInfo.setStartTimeOfDate(temp.getStartTimeOfDate());
            responseInfo.setSkillTimeId(temp.getTimeId());
            responseInfo.setShowTimeOfDate(temp.getStartTimeOfDate() + "-" + temp.getEndTimeOfDate());
            responseInfoList.add(responseInfo);
        });
        return responseInfoList;
    }

    private List<String> getImagesUrlList(String imagesUrl) {
        List<String> imagesList = new ArrayList<>();
        if (!StringUtils.isEmpty(imagesUrl)) {
            String[] str = imagesUrl.split(",");
            imagesList = Arrays.stream(str).collect(Collectors.toList());
        }
        return imagesList;
    }

    private SkillActivityConfig setSkillActivityConfig(SkillConfigAddRequest skillConfigAddRequest, String promotionId) {
        SkillActivityConfig skillActivityConfig = new SkillActivityConfig();
        BeanUtils.copyProperties(skillConfigAddRequest, skillActivityConfig);
        skillActivityConfig.setPromotionId(promotionId);
        String urlImages = "";
        if (CollectionUtils.isNotEmpty(skillConfigAddRequest.getImagesUrls())) {
            for (String url : skillConfigAddRequest.getImagesUrls()) {
                if (!StringUtils.isEmpty(url)) {
                    urlImages = url + "," + urlImages;
                }
            }
        }
        skillActivityConfig.setImagesUrls(urlImages);
        skillActivityConfig.setDeleteFlag(false);
        return skillActivityConfig;
    }

    private void insertBatchTime(List<SkillTimeInfo> timeInfoList, String promotionId) {
        if (CollectionUtils.isEmpty(timeInfoList)) {
            return;
        }
        timeInfoList.stream().forEach(temp -> {
            SkillActivityTimeConfig config = new SkillActivityTimeConfig();
            config.setEndTimeOfDate(temp.getEndTimeOfDate());
            config.setStartTimeOfDate(temp.getStartTimeOfDate());
            config.setPromotionId(promotionId);
            config.setTimeId(IDUtils.GenerateBillNo());
            config.setDeleteFlag(false);
            skillActivityTimeConfigService.insert(config);
        });
    }
}
